package com.xyzboom.tld;

import jakarta.servlet.jsp.JspException;
import jakarta.servlet.jsp.PageContext;
import jakarta.servlet.jsp.tagext.IterationTag;
import jakarta.servlet.jsp.tagext.Tag;
import jakarta.servlet.jsp.tagext.TagSupport;

public class ForTag extends TagSupport {
    private int end;
    private int start;
    private int i;
    private String var;
    private int step = 1;

    public String getVar() {
        return var;
    }

    public void setVar(String var) {
        this.var = var;
    }

    public int getEnd() {
        return end;
    }

    public void setEnd(int end) {
        this.end = end;
    }

    public int getStart() {
        return start;
    }

    public void setStart(int start) {
        this.start = start;
    }

    public int getStep() {
        return step;
    }

    public void setStep(int step) {
        this.step = step;
    }

    @Override
    public int doStartTag() throws JspException {
        i = start;
        pageContext.setAttribute(var, i, PageContext.PAGE_SCOPE);
//        return Tag.SKIP_BODY;//不执行标签体内容
        return Tag.EVAL_BODY_INCLUDE; //执行标签体内容
    }

    @Override
    public int doEndTag() throws JspException {
        return Tag.EVAL_PAGE;//执行JSP页面
    }

    @Override
    public int doAfterBody() throws JspException {
        if (i >= end) {
            pageContext.setAttribute(var, null, PageContext.PAGE_SCOPE);
            return IterationTag.SKIP_BODY;
        } else {
            i += step;
            pageContext.setAttribute(var, i, PageContext.PAGE_SCOPE);
            return IterationTag.EVAL_BODY_AGAIN;
        }
    }
}
